<template>
	<view>
		<view v-if='banner && banner.length > 0'>
			<u-swiper :list="banner" radius='0' height='158px'></u-swiper>
		</view>
		<!-- 菜单 -->
		<view v-if='contentCategories && contentCategories.length > 0' style='margin:10px 0px;'>
			<view v-for='category in contentCategories' style='margin-top:10px'>
				<u-row>
					<u-col v-for="(item,index) in category" span='3' @click='toUrl(`/pages/content/list?id=${item.id}`)'>
						<view class='icon'>
							<img :src='item.icon' style='width:60px;height:60px' />
							<view>{{item.name}}</view>
						</view>
					</u-col>
				</u-row>
			</view>
		</view>
		<view v-if='products && products.length > 0'>
			<u-divider text="主推产品"></u-divider>
			<view style='display: flex;flex-wrap: wrap;width:100%'>
				<view v-for='(item,index) in products' class='product-list' :key='index'>
					<view>
						<view style='background-color: #f3f3f3;border-radius: 5px;margin:5px;padding:10px'>
							<view class='image-container'>
								<image v-if='item.cover == null' :src="defaultImage" class='image-a'></image>
								<image v-else :src="item.cover" class='image-a'></image>
							</view>
							<view class='product-name'>
								{{item.name}}
							</view>
							<view>
								<u-row>
									<u-col span='6'>
										<view>
											<text class='price'>￥{{item.specifications[0].price}}</text>
										</view>
									</u-col>
									<u-col span='6' v-if='item.specifications && item.specifications.length == 1'>
										<view>
											<view v-if='item.quantity > 0'>
												<u-row>
													<u-col span='4'>
														<view class="minus" @click='pev(index)'>
															<u-icon name="minus" size="12"></u-icon>
														</view>
													</u-col>
													<u-col span='4'>
														<view style="text-align: center;" class="input">
															{{item.quantity}}
														</view>
													</u-col>
													<u-col span='4'>
														<view class="plus" @click='add(index)'>
															<u-icon name="plus" color="#FFFFFF" size="12"></u-icon>
														</view>
													</u-col>
												</u-row>
											</view>
											<view v-else>
												<u-row>
													<u-col span='4'>
														<view>
														</view>
													</u-col>
													<u-col span='4'>
														<view style="text-align: center;" class="input">
														</view>
													</u-col>
													<u-col span='4'>
														<view class="plus" @click='add(index)'>
															<u-icon name="plus" color="#FFFFFF" size="12"></u-icon>
														</view>
													</u-col>
												</u-row>
											</view>
										</view>
									</u-col>
									<u-col v-else span='6'>
										<view style='text-align: right;'>
											<text class='spec-btn' @click='chooseProduct(item)'>选规格</text>
										</view>
									</u-col>
								</u-row>
							</view>
						</view>
					</view>
				</view>

			</view>
		</view>
		<!-- 弹出需要选择的标签 -->
		<u-popup v-if='chooseProduct != ""' :show="showTag" @close="showTag = false" mode='bottom' round='10'>
			<view style='max-height: 65vh;padding: 20px 10px 30px 10px;overflow: auto;'>
				<u-divider :text="choosedProduct.name"></u-divider>
				<view>
					<view class="container">
						<view class="item" v-for='item in choosedProduct.specifications'>
							<view v-if='choosedSpec.id == item.id' class='spec-active'>
								{{item.name}}
							</view>
							<view v-else class='spec' @click='choosedSpec = item'>{{item.name}}</view>
						</view>
					</view>
				</view>
				<view style='padding:10px'>
					<u-row>
						<u-col span='6'>
							<view style='color:#ff9900'>
								￥{{choosedSpec.price}}
							</view>
						</u-col>
						<u-col span='6'>
							<view style='float: right;'>
								<u-number-box v-model="quantity">
									<view slot="minus" class="minus">
										<u-icon name="minus" size="12"></u-icon>
									</view>
									<text slot="input" style="width: 50px;text-align: center;"
										class="input">{{quantity}}</text>
									<view slot="plus" class="plus">
										<u-icon name="plus" color="#FFFFFF" size="12"></u-icon>
									</view>
								</u-number-box>
							</view>
						</u-col>
					</u-row>
				</view>
				<view style='padding-top:10px'>
					<u-button text='加入购物车' type='primary' @click='addSpec'></u-button>
				</view>
			</view>
		</u-popup>
	</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				banner: [],
				contentCategories: [],
				products: [],
				defaultImage: 'https://picture.jmgc.vip/4c0ca142-9573-4e44-999d-545f2c244c0d.png',
				showTag: false,
				choosedProduct: '',
				choosedSpec: '',
				quantity: 1,
				carts: [],
				recommendedUser: 2,
				myId: 0
			}
		},
		onShow() {
			let carts = uni.getStorageSync('carts')
			if (carts != '') {
				this.carts = carts
				uni.setTabBarBadge({
					index: 2,
					text: `${carts.length}`
				})
			} else {
				uni.removeTabBarBadge({
					index: 2
				})
			}
		},
		onShareAppMessage(res) {
			const userId = uni.getStorageSync('userId')
			console.log(userId)
			return {
				title: '一起拼个团',
				path: `/pages/index/index?recommendedUser=${userId}`,
				imageUrl: ''
			}
		},
		onLoad(options) {
			// 查是否有推荐人
			if(typeof(options.recommendedUser) != 'undefined'){
				this.recommendedUser = options.recommendedUser
				console.log('有推荐人信息',this.recommendedUser)
			}
			let token = uni.getStorageSync('api_token')
			if (token != '') {
				this.getHotProduct()
				this.getBanner()
				this.getContentCategory(1)
			}else{
				this.wxLogin()
			}
		},
		methods: {
			wxLogin(){
				let _this = this
				uni.login({
					provider: "weixin",
					success: function(res) {
						let data = {
							code: res.code
						}
						if(_this.recommendedUser > 0){
							data.recommendedUser = _this.recommendedUser
						}
						console.log('信息',data)
						_this.request.get("wechat/mini/login", data).then((res) => {
							if (res.data.token) {
								uni.setStorageSync('api_token', res.data.token)
								_this.getBanner()
								_this.getHotProduct()
								// 登录之后，要记录userId，方便分享时候添加
								_this.request.get(`api/user`).then((res) => {
									uni.setStorageSync('userId',res.data.id)
								})
								_this.checkStaff()
							}
						})
					},
				});
			},
			getContentCategory(page){
				console.log('page',page)
				this.request.get(`api/categories`,{
					'@filter': `entity.getType().getSlug() == 'content'`,
					'@order': `entity.sequence|ASC`,
					page: page,
					limit: 4
				}).then((res) => {
					if(page == 1){
						this.contentCategories = []
					}
					this.contentCategories.push(res.data)
					console.log('categories',this.contentCategories)
					if(res.data && res.data.length >= 4){
						this.getContentCategory(page + 1)
					}
				})
			},
			checkStaff(){
				// 看是否已经注册了staff，是的话，就不管，不是的话，就新建，避免之后的分账有问题
				this.request.get(`api/staffs`).then((res) => {
					console.log('sss',res.data)
					if(res.data == null || res.data.length == 0){
						console.log('需要新建staff')
						// 需要创建staff，看推荐人是否有，是的，用推荐人的squad，没有的，默认一个
						let squad = 1
						this.request.get(`public/staffs`,{
							'@filter': `entity.getUser().getId() == ${this.recommendedUser}`
						}).then((res) => {
							console.log('推荐人团队',res.data)
							if(res.data && res.data.length > 0){
								squad = res.data[0].squad.id
							}
							// 无任何信息，只可以用user的信息来先录入，到时候再更新
							this.request.get(`api/user`).then((res) => {
								console.log('user',res.data)
								const staff = {
									name: res.data.username,
									squad: squad
								}
								this.request.post(`api/staffs`,staff).then((res) => {
									console.log('创建staff成功')
								})
							})
							
						})
					}
				})
			},
			getBanner() {
				this.request.get(`public/albums`, {
					'@filter': `entity.getType() == 'INDEX-BANNER'`
				}).then((res) => {
					console.log('banner',res.data)
					let banner = []
					for (let i of res.data[0].pictures) {
						banner.push(i.image)
					}
					this.banner = banner
				})
			},
			getHotProduct() {
				uni.showLoading()
				this.request.get(`api/products`, {
					'@filter': `entity.getIsHot() == true && entity.getIsOnSale() == true`,
					'@display': ['name', 'cover', 'specifications']
				}).then((res) => {
					if(res.data.length == 0){
						uni.hideLoading()
					}
					if (res.data.length < this.limit) {
						this.status = 'nomore'
					}
					let carts = uni.getStorageSync('carts')
					for (let i of res.data) {
						i['quantity'] = 0
						if (carts != '') {
							for (let c of carts) {
								if (c.specId == i.specifications[0].id) {
									i['quantity'] = c.quantity
								}
							}
						}
						this.products.push(i)
						uni.hideLoading()
					}
					console.log('product', this.products)
				})
			},
			toUrl(page) {
				uni.navigateTo({
					url: page
				})
			},
			chooseProduct(product) {
				this.choosedProduct = product
				this.choosedSpec = product.specifications[0]

				this.showTag = true
			},
			add(index) {
				this.products[index].quantity++
				this.getCartData(index, this.products[index].specifications[0].id)
			},
			pev(index) {
				this.products[index].quantity--
				this.getCartData(index, this.products[index].specifications[0].id)
			},
			addSpec() {
				let had = false
				for (let i of this.carts) {
					if (i.specId == this.choosedSpec.id) {
						had = true
						i.quantity = this.quantity
					}
				}
				if (!had) {
					this.carts.push({
						specId: this.choosedSpec.id,
						specName: this.choosedSpec.name,
						cover: this.choosedProduct.cover,
						quantity: this.quantity,
						name: this.choosedProduct.name,
						price: this.choosedSpec.price
					})
				}
				uni.setStorageSync('carts', this.carts)
				uni.setTabBarBadge({
					index: 2,
					text: `${this.carts.length}`
				})
				this.showTag = false
				this.quantity = 1
			},
			getCartData(index, specId) {
				let product = this.products[index]
				let had = false
				let cartIndex = 0
				for (let i in this.carts) {
					if (this.carts[i].specId == specId) {
						had = true
						this.carts[i].quantity = this.products[index].quantity
						break
					}
				}
				if (!had) {
					this.carts.push({
						specId: specId,
						specName: this.products[index].specifications[0].name,
						cover: this.products[index].cover,
						quantity: this.products[index].quantity,
						name: this.products[index].name,
						price: this.products[index].specifications[0].price
					})
				}
				if (this.products[index].quantity <= 0) {
					this.carts.splice(cartIndex, 1)
				}
				if (this.carts.length > 0) {
					uni.setStorageSync('carts', this.carts)
					uni.setTabBarBadge({
						index: 2,
						text: `${this.carts.length}`
					})
				} else {
					uni.removeStorageSync('carts')
					uni.removeTabBarBadge({
						index: 2
					})
				}

			}
		}
	}
</script>

<style>
	.icon{
		text-align: center;
		color:#909399;
		font-size: 14px;
	}
	.product-list {
		width: 50%;
	}

	.image-container {
		display: flex;
		/* 使用 Flexbox 布局 */
		justify-content: center;
		/* 水平居中 */
		align-items: center;
		/* 垂直居中 */
		height: 150px;
		/* 或者您想要的高度，这里假设是全屏高度 */
		width: 100%;
		/* 容器宽度为100% */
	}

	.image-a {
		max-width: 100%;
		/* 图片最大宽度不超过容器 */
		max-height: 100%;
		/* 图片最大高度不超过容器 */
		object-fit: cover;
	}

	.product-name {
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 3;
		overflow: hidden;
		text-overflow: ellipsis;
		font-size: 15px;
		height: 60px;
		color:#909399;
		padding:10px 0px 10px 0px;
	}

	.price {
		color: #ff9900;
		padding-top: 10px;
	}

	.title {
		color: #606266;
		padding: 10px 0px;
	}

	.date {
		color: #909399;
		font-size: 14px;
	}

	.activity-list {
		background-color: #f3f3f3;
		margin: 10px;
		border-radius: 5px;
		padding: 10px;
	}

	.spec-btn {
		background-color: #19be6b;
		font-size: 12px;
		color: #fff;
		padding: 3px 10px;
		border-radius: 14px;
	}

	.plus {
		width: 30px;
		height: 30px;
		background-color: #19be6b;
		border-radius: 50%;
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		justify-content: center;
		align-items: center;
	}

	.container {
		display: flex;
		flex-wrap: wrap;
	}

	.item {
		margin: 5px;
	}

	.spec-active {
		font-size: 14px;
		padding: 3px 10px;
		border-radius: 5px;
		background-color: #19be6b;
		color: #fff
	}

	.spec {
		font-size: 14px;
		padding: 3px 10px;
		border-radius: 5px;
		background-color: #909399;
		color: #fff;
	}

	.minus {
		width: 30px;
		height: 30px;
		background-color: #fff;
		border-radius: 50%;
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		justify-content: center;
		align-items: center;
	}
</style>